
axios.interceptors.request.use(
    (config) => {  //这个回调函数 在每次发请求到服务器端之前 都会调用执行
        //设置请求头参数
        config.headers['Authorization'] = 'Bearer' + ' ' + localStorage.getItem('token');
        return config;
    },
    (error) => {
        return Promise.reject(error)
    }
)
axios.interceptors.response.use(
    (res) => {
        return res
    },

    (error) => {
        if (error.response.status == 401) {
            alert('登录过期!需要重新登录')
            location.href = './login.html'
            localStorage.removeItem('token')
        } else if (error.response.status == 404) {
            alert('访问路径有误！')
        } else if (error.response.status == 500) {
            alert('服务器内部错误')
        }
        return Promise.reject(error)
    }
)
//获取搜索按钮
var inputBtn = document.querySelector('.inputbox button')
//获取输入框
var inputEle = document.querySelector('.inputbox input')
//获取localStorage中存储的用户信息
var userinfo = JSON.parse(localStorage.getItem('userinfo'))
//渲染用户信息到首页
document.querySelector('.username').innerHTML = userinfo.phone

inputBtn.onclick = () => {
    axios.get('/user/search', { params: { searchkey: inputEle.value } }).then((res) => {
        render(res.data.list)
        console.log(res.data);
    })
}
//给tbody添加点击事件(事件委托)
var tablebody = document.querySelector('tbody')
tablebody.onclick = (e) => {
    if (e.target.tagName == 'SPAN' && e.target.classList.contains('icon-shanchu')) {
        axios.post('/user/delete', { phone: e.target.dataset.phone }).then((res) => {
            console.log(res.data);
            render(res.data.list)
        })
    }
}
//渲染列表
function render(data) {
    var str = ''
    var num = 1
    var shu = 1
    str = data.map((item, index) => {
        return `<tr>
                    <td>${num++}</td>
                    <td>ceo</td>
                    <td>${item.phone}</td>
                    <td>${shu++}</td>
                    <td>正常</td>
                    <td> <span class="statusok">2022-10-19 20:56:47</span> </td>
                    <td> <span class="iconfont icon-bianji editicon" id="101">修改</span><span class="iconfont icon-shanchu deleteicon" data-phone="${item.phone}">删除</span></td>
                </tr>
        `
    }).join('')
    document.querySelector('tbody').innerHTML = str
}
var page = 1
axios.get('/user/list', { params: { page: page, count: 5 } }).then((res) => {

    render(res.data.list)
    console.log(res.data);
})


var next = document.querySelector('.next')
next.onclick = function () {
    page++
    axios.get('/user/list', { params: { page: page, count: 5 } }).then((res) => {
        render(res.data.list)
    })

}
// 上一页
var prev = document.querySelector('.prev')
prev.onclick = function () {
    page--
    if (page <= 0) {
        page = 1
    }
    axios.get('/user/list', { params: { page: page, count: 5 } }).then((res) => {
        render(res.data.list)
    })
}

axios.post('/user/login', { phpne: '18292956504', pass: '1234' }).then((res) => {
    console.log(res.data);
})